<template>
    <div class="edit" v-loading="loading" element-loading-text="加载中"
        element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
        <div class="edit_header">
            <span class="title">基础信息</span>
        </div>
        <el-form :model="jcxxForm" :rules="jcxxRules" ref="jcxxForm" label-width="100px" size="mini"
            :hide-required-asterisk="true">
            <el-row :gutter="20" style="margin-bottom:40px">
                <el-col :span="7">
                    <div class="descriptions">
                        <el-form-item prop="workOrderCode">
                            <template slot='label'>
                                <span style="color: red">*</span>
                                工单编号
                            </template>
                            <el-select v-model="jcxxForm.workOrderCode" 
                                disabled
                                >
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="processCode">
                            <template slot='label'>
                                <span style="color: red">*</span>
                                工序名称
                            </template>
                            <el-select v-model="jcxxForm.processCode"  
                                disabled
                                >
                            </el-select>
                        </el-form-item>
                        <el-form-item label="工序状态" prop="processState">
                            <el-radio-group v-model="jcxxForm.processState" @change="handleState">
                                <el-radio :label="0">未开始</el-radio>
                                <el-radio :label="1">执行中</el-radio>
                                <el-radio :label="2">已结束</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item prop="produceUser">
                            <template slot='label'>
                                <span style="color: red">*</span>
                                生产人员
                            </template>
                            <search-input :url="'/produce/work_report_add_get'" :placeholder="'请选择'"
                                :prop="'produceUser'" :proCode='proCode' :code="jcxxForm.produceUser"
                                :disabled='disState.prod_users' @handleChange='handleChange' ref="productUser">
                            </search-input>
                        </el-form-item>
                        <el-form-item label="报工数" prop="reportNumber">
                            <el-input-number v-model="jcxxForm.reportNumber" controls-position="right" size="mini"
                                placeholder='请填写' :min="0" :disabled='disState.planNum'>
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="良品数" prop="goodProductNumber">
                            <el-input-number v-model="jcxxForm.goodProductNumber" controls-position="right" size="mini"
                                placeholder='请填写' :min="0" @change="numberChange" :disabled='disState.goodNum'>
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="不良品数" prop="badProductNumber">
                            <el-input-number v-model="jcxxForm.badProductNumber" controls-position="right" size="mini"
                                placeholder='请填写' :min="0" @change="numberChange" :disabled='disState.badNum'>
                            </el-input-number>
                        </el-form-item>
                        <el-form-item label="不良品项" prop="badProductList" class='special'>
                            <el-select v-model="jcxxForm.badProductList" multiple placeholder="请选择"
                                popper-class='specialSelect' @visible-change='getBadPro'
                                :disabled='disState.badNumList'>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="工序进度" prop="gxjd">
                            <el-input v-model="jcxxForm.gxjd" disabled></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="7">
                    <div class="descriptions">
                        <el-form-item label="产品编号" prop="cpbh">
                            <el-input v-model="jcxxForm.cpbh" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="产品名称" prop="cpmc">
                            <el-input v-model="jcxxForm.cpmc" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="产品规格" prop="cpgg">
                            <el-input v-model="jcxxForm.cpgg" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="开始时间" prop="startTime">
                            <el-date-picker v-model="jcxxForm.startTime" type="datetime" format='yyyy-MM-dd HH:mm'
                                @change="difference(jcxxForm.startTime,jcxxForm.endTime)" :disabled='disState.s_time'>
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="endTime">
                            <el-date-picker v-model="jcxxForm.endTime" type="datetime" format='yyyy-MM-dd HH:mm'
                                @change="difference(jcxxForm.startTime,jcxxForm.endTime)" :disabled='disState.e_time'>
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="报工时长" prop="bgsc">
                            <div class="chooseTime">
                                <code class="hours">
                                    <el-input v-model="hours" :disabled='disState.r_hours' readonly></el-input>
                                    <span>小时</span>
                                </code>
                                <code class="min">
                                    <el-input v-model="min" :disabled='disState.r_hours' readonly></el-input>
                                    <span>分钟</span>
                                </code>
                            </div>
                        </el-form-item>
                        <el-form-item label="标准效率" class='efficiency' v-show='workingHours'>
                            <el-input v-model="output" disabled></el-input>
                            <span style='margin:0 5px'>/</span>
                            <el-input v-model="efficiencyHour" disabled></el-input>
                            <span style='margin:0 5px'>小时</span>
                            <el-input v-model="efficiencyMinute" disabled></el-input>
                            <span style='margin:0 5px'>分钟</span>
                            <el-input v-model="efficiencySecond" disabled></el-input>
                            <span style='margin:0 5px'>秒</span>
                        </el-form-item>
                        <el-form-item label="标准效率" v-show='!workingHours'>
                            <span style='color:rgba(0,0,0,.65)'>未配置</span>
                        </el-form-item>
                        <el-form-item label="实际效率" class='efficiency' v-show='hours > 0 || min > 0'>
                            <el-input v-model="realOutput" disabled></el-input>
                            <span style='margin:0 5px'>/</span>
                            <el-input v-model="realHour" disabled></el-input>
                            <span style='margin:0 5px'>小时</span>
                            <el-input v-model="realMinute" disabled></el-input>
                            <span style='margin:0 5px'>分钟</span>
                            <el-input v-model="realSecond" disabled></el-input>
                            <span style='margin:0 5px'>秒</span>
                        </el-form-item>
                        <el-form-item label="实际效率" v-show='hours <= 0 && min <= 0'>
                            <span style='color:rgba(0,0,0,.65)'>报工时长为0，无法计算效率</span>
                        </el-form-item>
                        <el-form-item label="达标率" prop="standardRate">
                            <el-input v-model="jcxxForm.standardRate" disabled></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="7">
                    <div class="descriptions">
                        <el-button type="text" class="record" icon="el-icon-s-operation" @click="watchHistory">查看操作记录
                        </el-button>
                    </div>
                </el-col>
            </el-row>
            <template>
                <el-row :gutter="20" style="margin-bottom:10px">
                    <el-col :span="7">
                        <div class="title">绩效信息</div>
                    </el-col>
                    <el-col :span="7">
                        <div class="title">自定义字段信息</div>
                    </el-col>
                </el-row>
            </template>
            <el-row :gutter="20">
                <el-col :span="7">
                    <div class="descriptions">
                        <el-form-item label="计价方式" prop="pricingMethod">
                            <el-radio-group v-model="jcxxForm.pricingMethod" :disabled='disState.pri_method'
                                @change="priceChange">
                                <el-radio :label="0">计件</el-radio>
                                <el-radio :label="1">计时</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="工资单价" prop="unitPrice" class='unitPrice'>
                            <el-input v-model="jcxxForm.unitPrice" disabled class='unitPrice'></el-input>
                            <el-button icon="el-icon-refresh-left" size="mini"
                                type='primary'
                                @click='refresh'
                                :disabled='disState.ref_btn'>
                                刷新</el-button>
                        </el-form-item>
                        <el-form-item label="预计工资" prop="estimateWage">
                            <el-input v-model="jcxxForm.estimateWage" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="审批状态" prop="verifyState">
                            <el-radio-group v-model="jcxxForm.verifyState" :disabled='disState.ver_state'>
                                <el-radio :label="0">未审批</el-radio>
                                <el-radio :label="1">已审批</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="审批人" prop="spr">
                            <el-input v-model="jcxxForm.spr" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="报工时间" prop="reportDate">
                            <el-date-picker v-model="jcxxForm.reportDate" type="datetime"
                                value-format='yyyy-MM-dd HH:mm:ss' :disabled='disState.rep_time'>
                            </el-date-picker>
                        </el-form-item>
                        <div class="goBack">
                            <el-button type="primary" size="mini" plain
                                @click="handleCancel">取 消</el-button>
                            <!-- <el-button type="primary" size="mini" plain>继续报工</el-button> -->
                            <el-button type="primary" size="mini" @click="jobHandle">保 存</el-button>
                        </div>
                    </div>
                </el-col>
                <el-col :span="7">
                    <div class="descriptions">
                        <!-- ====================自定义==================== -->
                        <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName'
                            :prop="item.id" v-show='hiddenRule(item)'>
                            <el-checkbox-group v-show="false" v-model="jcxxForm[item.id]"></el-checkbox-group>
                            <template slot='label'>
                                <span style="color: red" v-show="requireRsterisk(item)">*</span>
                                {{ item.chineseName }}
                                <el-tooltip class="item" effect="dark" :content="item.tips" placement="top"
                                    v-show='item.tips'>
                                    <span class="iconfont icon-wenhao wenhao"></span>
                                </el-tooltip>
                            </template>
                            <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
                                @uploadProgress='uploadProgress' ref='formLibrary' @getFormula='getFormula'>
                            </formLibrary>
                        </el-form-item>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 添加不良品项 -->
        <common-dialog ref='addBadPro' :width="530">
            <template #title>
                <span class="title">添加不良品项</span>
            </template>
            <template #body>
                <el-input placeholder="可搜索不良品项名称" suffix-icon="el-icon-search" size="mini" v-model="searchVal"
                    style="margin-bottom:10px" @input="searchBadPro">
                </el-input>
                <el-table :data="badProData" border style="width: 100%;" max-height="220"
                    :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                    :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}">
                    <el-table-column label="不良品项" prop='blpx'>
                        <template slot-scope="scope">
                            <el-checkbox v-model="scope.row.checked">{{scope.row.blpx}}
                            </el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量">
                        <template slot-scope='scope'>
                            <el-input-number v-model="scope.row.number" controls-position="right" size="mini"
                                placeholder='请填写' :min="0" style="width:80%">
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <div slot="empty">
                        <el-empty :image-size='100'></el-empty>
                    </div>
                </el-table>
            </template>
            <template #footer>
                <span>
                    <el-button type="plain" size="mini" @click="addBad">取 消</el-button>
                    <el-button type="primary" size="mini" @click="addBad">确 定</el-button>
                </span>
            </template>
        </common-dialog>
    </div>
</template>

<script>
    import {
        reportBadProduct,
        workReportHandle,
        reportDetail,
        wageMatch,
        calc
    } from '@/api/produceController'
    import {
        loginUserMess
    } from '@/api/loginController'
    import {
        customFieldOther,
        fillFieldMess
    } from '@/api/customFieldController'
    import searchInput from './searchInput.vue'
    import commonDialog from './dialog.vue'
    import formLibrary from '@/components/formLibrary'
    export default {
        data() {
            var badProductNumber = (rule, value, callback) => {
                if (this.jcxxForm.badProductList.length != 0) {
                    if (value == 0 || value == undefined) {
                        return callback(new Error('不良品数、不良品项需同时填写'));
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            };
            var badProductList = (rule, value, callback) => {
                if (this.jcxxForm.badProductNumber != 0 && this.jcxxForm.badProductNumber != undefined) {
                    if (!value.length) {
                        return callback(new Error('不良品数、不良品项需同时填写'));
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            };
            var dateCheck = (rule, value, callback) => {
                if (new Date(this.jcxxForm.startTime) > new Date(value)) {
                    return callback(new Error('结束时间需大于开始时间'));
                } else {
                    callback()
                }
            };
            return {
                disState: {
                    prod_users: true,
                    planNum: true,
                    goodNum: true,
                    badNum: true,
                    badNumList: true,
                    s_time: true,
                    e_time: true,
                    r_hours: true,
                    pri_method: true,
                    ref_btn: true,
                    ver_state: true,
                    rep_time: true,
                },
                jcxxForm: {
                    workOrderCode: '',
                    processCode: '',
                    processState: 0,
                    produceUser: '',
                    reportNumber: undefined,
                    goodProductNumber: 0,
                    badProductNumber: 0,
                    badProductList: [],
                    gxjd: '',
                    cpbh: '',
                    cpmc: '',
                    cpgg: '',
                    startTime: new Date(),
                    endTime: new Date(),
                    standardEfficiency: '',
                    actualEfficiency:'',
                    bgsc: '',
                    standardRate: '-',
                    pricingMethod: 0,
                    unitPrice: 0,
                    estimateWage: 0,
                    verifyState: 1,
                    spr: '',
                    reportDate: new Date().dateFormat('yyyy-MM-dd hh:mm:ss'),
                    unfinishedReason: ''
                },
                hours: 0,
                min: 0,
                disabled: false,
                jcxxRules: {
                    workOrderCode: [{
                        required: true,
                        message: '请选择工单',
                    }],
                    processCode: [{
                        required: true,
                        message: '请选择工序',
                    }],
                    produceUser: [{
                        required: true,
                        message: '请选择生产人员',
                    }],
                    badProductNumber: [{
                        validator: badProductNumber,
                        trigger: 'change'
                    }],
                    badProductList: [{
                        validator: badProductList,
                        trigger: 'change'
                    }],
                    startTime: [{
                        validator: dateCheck,
                    }],
                    endTime: [{
                        validator: dateCheck,
                    }],
                },
                loading: false,
                badProData: [],
                tempData: [],
                searchVal: '',
                proCode: '',
                map_badProductList: [],
                mapProcessState: {
                    '未开始': 0,
                    '执行中': 1,
                    '已结束': 2,
                },
                mapVerifyState: {
                    '未审批': 0,
                    '已审批': 1
                },
                piecePriceList: [],
                customFiledList: [],
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '', // 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                processName: '',
                producerName: '',
                userMess: {},
                uploadFlag: true,
                wagesId:'',
                workingHours:'',
                output:0,
                efficiencyHour:'',
                efficiencyMinute:'',
                efficiencySecond:'',
                realOutput:'',
                realHour:1,
                realMinute:0,
                realSecond:0,
                totalDuration:0,
                percentage:0,
                indexCount:0
            }
        },
        components: {
            commonDialog,
            searchInput,
            formLibrary
        },
        watch: {
            jcxxForm: {
                handler() {
                    this.hiddenRule('')
                },
                deep: true,
            }
        },
        mounted() {
            this.getReportDetail({
                id: this.$route.query.id
            })
        },
        methods: {
            // 自定义字段
            getCustomFieldOther() {
                customFieldOther({
                    type: 'workReport'
                }).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if (res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${报工./g, 'formItemData["').replace(/\}/g, '"]')
                                .replace(/\${用户信息./g, 'userFormItemData["')
                            item.id = item.id + ''
                            let obj = {}
                            if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if(item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.jcxxForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.jcxxForm[item.id]).slice(0,index) : String(this.jcxxForm[item.id])
                                    if (!this.jcxxForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.jcxxForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.jcxxForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.jcxxRules = Object.assign(this.jcxxRules, obj)
                            if (item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.getLoginUserMess()
                    }
                })
            },
            // 用户信息
            getLoginUserMess(data) {
                loginUserMess(data).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userMess = res.data
                    }
                })
            },
            
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for (let key in this.jcxxForm) {
                        if (Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.jcxxForm[key]
                            })
                        }
                    }
                    if (res.code == 200) {
                        // 如果该条数据有自定义字段
                        if (res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => {
                                    return res.customFieldId == item.from
                                })
                                if (f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if (k.customFieldId == item.from) {
                                            this.jcxxForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j
                                                .customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.jcxxForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if (k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => {
                                                return res.id == item.to
                                            })
                                            if (d.fieldType == 'picture' || d.fieldType ==
                                                'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.jcxxForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => {
                                            return res.id == item.to
                                        })
                                        if (d.fieldType == 'picture' || d.fieldType ==
                                            'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                                })
                                this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if (item.objectFieldId == n) {
                                this.jcxxForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item
                                    .id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.jcxxForm, d.name, d.value)
                // 操作的是关联对象
                if (d.relevanceObject != undefined) {
                    if (d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if (item.objectFieldId == d.name) {
                                this.jcxxForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for (let key in this.jcxxForm) {
                            let ind = this.defaultData.findIndex(res => {
                                return res.customFieldId == key
                            })
                            if (ind != -1) {
                                this.$set(this.defaultData, ind, {
                                    customFieldId: key,
                                    value: this.jcxxForm[key]
                                })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.jcxxForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '工单编号': this.jcxxForm.workOrderCode,
                    '工序名称': this.processName,
                    '报工数': this.jcxxForm.reportNumber,
                    '良品数': this.jcxxForm.goodProductNumber,
                    '生产人员': this.producerName,
                    '产品编号': this.jcxxForm.cpbh,
                    '产品名称': this.jcxxForm.cpmc,
                    '产品规格': this.jcxxForm.cpgg,
                    '开始时间': this.utils.formatTime(this.jcxxForm.startTime,
                        'yyyy-MM-dd hh:mm'),
                    '结束时间': this.utils.formatTime(this.jcxxForm.endTime,
                        'yyyy-MM-dd hh:mm')
                }
                let userFormItemData = {
                    '账号': this.userMess.account,
                    '姓名': this.userMess.name,
                    '手机号': this.userMess.mobile,
                    '角色': this.userMess.role,
                }
                this.customFiledList.map(item => {
                    if (formItemData[item.chineseName] == undefined) {
                        if (this.jcxxForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.jcxxForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                    if (userFormItemData[item.chineseName] == undefined) {
                        if (this.jcxxForm[item.id] != undefined) {
                            userFormItemData[item.chineseName] = this.jcxxForm[item.id]
                        } else {
                            userFormItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.jcxxRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.jcxxRules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.jcxxRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.jcxxRules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if (Number(v)) {
                    let id = ''
                    data.map(item => {
                        if (item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },
            //公式
            getFormula(name,id){
                let customFieldVos = []
                let customData = this.getCustom() 
                for (const key in customData) {
                    customFieldVos.push({
                        customFieldId: key,
                        value: customData[key]
                    })
                }
                let workReportString = Object.assign(this.jcxxForm,{customFieldVos})
                let data = Object.assign({cuColumnName:name},{workReportString:JSON.stringify(workReportString)})
                this.getCalc(data,id)
            },
            //公式计算
            getCalc(data,id) {
                calc(data,id).then(res => {
                    if (res.code == 200) {
                        this.defaultData = []
                        for(let key in this.jcxxForm) {
                            if(key == Number(key)) {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.jcxxForm[key]
                                })
                            }
                        }
                        let n = this.defaultData.findIndex(i => i.customFieldId == id)
                        if(n != -1) {
                            this.$set(this.defaultData,n,{customFieldId:id,value:res.data})
                        }else{
                            this.defaultData.push({
                                customFieldId:id,
                                value:res.data
                            })
                        }
                        this.$set(this.jcxxForm, id, res.data)
                    }
                })
            },
            //获取报工不良品项
            getReportBadProduct(data) {
                reportBadProduct(data).then(res => {
                    if (res.code == 200) {
                        this.tempData = res.data.map(i => {
                            return {
                                id: i.id,
                                blpx: i.name,
                                checked: false,
                                number: undefined,
                            }
                        })
                        let nameArr = []
                        let numArr = []
                        nameArr = this.jcxxForm.badProductList.length && this.jcxxForm.badProductList.map(
                            i => {
                                return i.split(' ')[0]
                            })
                        numArr = this.jcxxForm.badProductList.length && this.jcxxForm.badProductList.map(
                            i => {
                                return i.split(' ')[1]
                            })
                        nameArr.length && this.tempData.forEach((item, index) => {
                            if (nameArr.indexOf(item.blpx) != -1) {
                                this.tempData[index].checked = true
                                this.tempData[index].number = numArr[this.indexCount]
                                ++ this.indexCount
                            }
                        })
                        this.badProData = this.tempData
                    }
                })
            },
            //报工详情
            getReportDetail(data) {
                this.loading = true
                reportDetail(data).then(res => {
                    if (res.code == 200) {
                        this.$refs.productUser.getDataList({
                            code: this.$route.query.code,
                            name: ''
                        })
                        this.getCustomFieldOther()
                        this.processName = res.data.processName
                        this.missionId = res.data.missionId
                        this.jcxxForm.workOrderCode = res.data.workOrderCode
                        this.jcxxForm.processCode = res.data.processName
                        this.jcxxForm.processState = this.mapProcessState[res.data.processState]
                        this.jcxxForm.produceUser = res.data.produceUser
                        this.jcxxForm.reportNumber = res.data.reportNumber
                        this.jcxxForm.goodProductNumber = res.data.goodProductNumber
                        this.jcxxForm.badProductNumber = res.data.badProductNumber
                        this.jcxxForm.gxjd = `${res.data.goodProductNumber} / ${res.data.planedNumber}`
                        this.jcxxForm.cpbh = res.data.productCode
                        this.jcxxForm.cpmc = res.data.productName
                        this.jcxxForm.cpgg = res.data.productSpecification
                        this.jcxxForm.startTime = res.data.reportStartTime
                        this.jcxxForm.endTime = res.data.reportEndTime
                        this.jcxxForm.pricingMethod = res.data.pricingMethod
                        this.jcxxForm.unitPrice = res.data.unitPrice
                        this.jcxxForm.verifyState = this.mapVerifyState[res.data.verifyState]
                        this.jcxxForm.spr = res.data.verifyName
                        this.jcxxForm.reportDate = res.data.verifyTime
                        this.jcxxForm.unfinishedReason = res.data.unfinishedReason
                        if (res.data.list == null) {
                            this.jcxxForm.badProductList = []
                        } else {
                            this.jcxxForm.badProductList = res.data.list.map(i => {
                                return `${i.name} ${i.num}`
                            })
                            this.map_badProductList = res.data.list.map(i => {
                                return {
                                    badProductId: i.badProductId,
                                    num: i.num,
                                }
                            })
                        }
                        this.proCode = this.$route.query.code
                        this.difference(res.data.reportStartTime, res.data.reportEndTime)
                        this.handleState(this.mapProcessState[res.data.processState])
                        this.customFiledData = []
                        this.defaultData = []
                        let custom = {}
                        // 不为null说明该条数据有自定义字段，将自定义字段值初始化给表单
                        if (res.data.customFieldVos != null) {
                            res.data.customFieldVos.map(item => {
                                custom[item.customFieldId] = item.value //绩效工资匹配规则含有自定义字段时
                                this.$set(this.jcxxForm, item.customFieldId, item.value)
                                this.customFiledData.push({
                                    customFieldId: item.customFieldId,
                                    value: item.value
                                })
                                this.defaultData.push({
                                    customFieldId: item.customFieldId,
                                    value: item.value
                                })
                            })
                        }
                        this.getWageMatch({
                            pricing:res.data.pricingMethod,
                            missionId:res.data.missionId,
                            userId:res.data.produceUser,
                            wordOrderCode:res.data.workOrderCode,
                            custom
                        })
                    }
                    this.loading = false
                })
            },
            //报工操作
            getWorkReportHandle(data) {
                workReportHandle(data).then(res => {
                    if (res.code == 200) {
                        this.$router.push('/productionManagement/jobBooking')
                        this.utils.showMsg('报工编辑成功', 'success')
                    }
                })
            },
            //工资绩效匹配
            getWageMatch(data) {
                const {pricingMethod,goodProductNumber} = this.jcxxForm
                this.loading = true
                wageMatch(data).then(res => {
                    if (res.code == 200) {
                        if(res.data.workingHours){ //计价或计时标准效率有值时 实际效率时长和标准效率相同 反之 默认值
                            let str = res.data.workingHours
                            let hour = Number(str.substring(0, str.indexOf('时')-1))
                            let time = str.substring(str.indexOf('时')+1, str.length-1).split('分钟')
                            this.output = res.data.output
                            this.efficiencyHour = hour
                            this.efficiencyMinute = time[0]
                            this.efficiencySecond = time[1]
                            this.realHour = hour
                            this.realMinute = time[0]
                            this.realSecond = time[1]
                        }else{ //默认值
                            this.realHour = 1
                            this.realMinute = 0
                            this.realSecond = 0
                        }
                        this.jcxxForm.unitPrice = res.data.unitPrice || 0
                        const {unitPrice} = this.jcxxForm
                        this.jcxxForm.estimateWage = pricingMethod ? //计价方式改变时重新算一下预计工资
                            (this.hours + (this.min / 60)).toFixed(2) * unitPrice : goodProductNumber *
                            unitPrice
                        this.wagesId = res.data.id || ''
                        this.workingHours = res.data.workingHours || ''
                        //总时长 若当前工序计件和计时都未配置标准效率时 若报工时长!=0时 默认实际效率的时长为1h0min0s 反之和标准效率时长一样
                        this.totalDuration = res.data.workingHours ? (this.efficiencyHour + (this.efficiencyMinute / 60) + (this.efficiencySecond / 3600))
                            : 1
                        //占比 报工时长 / 总时长
                        this.percentage = (this.hours + (this.min / 60)) / this.totalDuration
                        //实际效率
                        this.realOutput = (goodProductNumber / this.percentage).toFixed(2)
                        //达标率
                        if(this.hours == 0 && this.min == 0){ //报工时长==0
                            this.jcxxForm.standardRate == '-'
                        }else if(this.hours > 0 || this.min > 0){ //报工时长>0 && 标准效率有值时
                            this.jcxxForm.standardRate = res.data.workingHours ? 
                                (((goodProductNumber / this.percentage) / this.output) * 100).toFixed(2) + '%' : '-'
                        }
                    }
                    this.loading = false
                })
            },
            //绩效工资匹配规则含有自定义字段时获取该值
            getCustom(){
                let custom = {}
                for (let key in this.jcxxForm) {
                    if (Number(key)) {
                        this.customFiledList.forEach(item => {
                            if (
                                item.id == key && this.jcxxForm[key] != null &&
                                String(this.jcxxForm[key]).length
                            ) {
                                custom[item.id] = this.jcxxForm[key]
                            }
                        })
                    }
                }
                return custom
            },
            //计价方式
            priceChange(v) {
                this.getWageMatch({
                    pricing:v,
                    missionId:this.missionId,
                    userId:this.jcxxForm.produceUser,
                    wordOrderCode:this.jcxxForm.workOrderCode,
                    custom:this.getCustom()
                })
            },
            //searchinput变化时
            handleChange(v) {
                this.jcxxForm.produceUser = v.v
                this.producerName = v.name
                this.getWageMatch({
                    pricing: this.jcxxForm.pricingMethod,
                    missionId: this.missionId,
                    userId:v.v,
                    wordOrderCode: this.jcxxForm.workOrderCode,
                    custom:this.getCustom()
                })
            },
            //设置禁用状态
            handleState(val) {
                for (let key in this.disState) {
                    this.disState[key] = val != 1
                }
            },
            //报工操作处理
            jobHandle() {
                this.$refs.jcxxForm.validate((valid) => {
                    if (valid) {
                        /**
                         * 说明：-----------
                         * 当前选择工序按照绩效工资匹配规则匹配上时,该工序显示相应标准效率
                         * 实际效率根据报工时长--当报工时长!=0时,显示实际效率
                            *报工时长!=0&&标准效率为空&&良品数==0 实际效率==0.00/1h/0min/0s
                            *报工时长!=0&&标准效率为空&&良品数!=0 实际效率==良品数/(报工时长/1h)
                            *报工时长!=0&&标准效率不为空&&良品数==0 实际效率==0.00/(同标准效率时长配置)
                            *报工时长!=0&&标准效率不为空&&良品数!=0 实际效率==良品数/(报工时长/同标准效率时长配置)
                         * 实际效率根据报工时长--当报工时长==0时,不显示实际效率
                         * 达标率 当标准效率=='未配置'或实际效率=='报工时长为0，无法计算效率' 达标率=='-'
                         * 达标率 当标准效率!='未配置'且实际效率!='报工时长为0，无法计算效率' 达标率== (良品数/(报工时长/同标准效率时长配置)) / 标准效率产出标准
                         */
                        this.jcxxForm.standardEfficiency = this.workingHours ?
                            this.output + ' / ' + this.efficiencyHour + '时' + this.efficiencyMinute + '分钟' + this.efficiencySecond + '秒'
                            : ''
                        if(this.hours > 0 || this.min > 0){
                            this.jcxxForm.actualEfficiency = 
                                this.realOutput + ' / ' + this.realHour + '时' + this.realMinute + '分钟' + this.realSecond + '秒'
                        }else if(this.hours == 0 && this.min == 0){
                            this.jcxxForm.actualEfficiency = ''
                        }
                        let data = {
                            id: this.$route.query.id,
                            wagesId: this.wagesId,
                            processState: this.jcxxForm.processState,
                            produceUser: this.jcxxForm.produceUser,
                            reportNumber: this.jcxxForm.reportNumber,
                            goodProductNumber: this.jcxxForm.goodProductNumber || 0,
                            badProductNumber: this.jcxxForm.badProductNumber || 0,
                            badProductList: this.map_badProductList,
                            startTime: this.utils.formatTime(this.jcxxForm.startTime,
                                'yyyy-MM-dd hh:mm:ss'),
                            endTime: this.utils.formatTime(this.jcxxForm.endTime, 'yyyy-MM-dd hh:mm:ss'),
                            pricingMethod: this.jcxxForm.pricingMethod,
                            verifyState: this.jcxxForm.verifyState,
                            reportDate: this.jcxxForm.reportDate,
                            unfinishedReason: this.jcxxForm.unfinishedReason,
                            standardRate:this.jcxxForm.standardRate,
                            standardEfficiency:this.jcxxForm.standardEfficiency,
                            actualEfficiency:this.jcxxForm.actualEfficiency
                        }
                        let customData = []
                        for (let key in this.jcxxForm) {
                            if (Number(key)) {
                                this.customFiledList.find(item => {
                                    if (
                                        item.id == key && this.jcxxForm[key] != null &&
                                        String(this.jcxxForm[key]).length
                                    ) {
                                        customData.push({
                                            customFieldId: item.id,
                                            value: this.jcxxForm[key]
                                        })
                                    }
                                })
                            }
                        }
                        // 关联对象后，判断单选框/复选框关联过来的值是否存在
                        this.customState = true
                        this.customErrorLabel = ''
                        this.customFiledList.map(item => {
                            // 单选框
                            if (item.fieldType == 'selectRadio') {
                                if (this.jcxxForm[item.id] != '' && this.jcxxForm[item.id] !=
                                    undefined) {
                                    let s = JSON.parse(item.checkBox).find(res => {
                                        return this.jcxxForm[item.id] == res.value
                                    })
                                    if (s == undefined) {
                                        this.customState = false
                                        this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                    }
                                }
                            }
                            // 复选框
                            if (item.fieldType == 'selectChecked') {
                                if (this.jcxxForm[item.id] != '' && this.jcxxForm[item.id] !=
                                    undefined && this.jcxxForm[item.id] != '[]') {
                                    JSON.parse(this.jcxxForm[item.id]).map(k => {
                                        let s = JSON.parse(item.checkBox).find(res => {
                                            return res.value == k
                                        })
                                        if (s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName +
                                                '】选项值不正确'
                                        }
                                    })
                                }
                            }
                        })
                        data.customFieldVos = customData
                        if (this.customState) {
                            if (this.uploadFlag) {
                                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                                    k.removeData('ok')
                                })
                                this.getWorkReportHandle(data)
                            } else {
                                this.utils.showMsg('正在上传，请稍后', 'warning')
                            }
                        } else {
                            this.utils.showMsg(this.customErrorLabel, 'error')
                        }
                    } else {
                        return false;
                    }
                })
            },
            // 取消
            handleCancel() {
                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                    k.removeData('cancle')
                })
                this.$router.push('/productionManagement/jobBooking')
            },
            //搜索不良品项名称
            searchBadPro() {
                //需要有一个中间变量接收 不然数据越搜越少
                this.badProData = this.tempData.filter(data =>
                    !this.searchVal || data.blpx.toLowerCase().includes(this.searchVal.toLowerCase()))
            },
            //添加不良品项
            getBadPro(flag) {
                if (flag) {
                    this.indexCount = 0
                    this.$refs.addBadPro.openDialog()
                    this.getReportBadProduct({
                        processCode:this.proCode,
                        limit: 3,
                        page: 1
                    })
                }
            },
            //刷新
            refresh(){
                this.getWageMatch({
                    pricing: this.jcxxForm.pricingMethod,
                    missionId: this.missionId,
                    userId:this.jcxxForm.produceUser,
                    wordOrderCode:this.jcxxForm.workOrderCode,
                    custom:this.getCustom()
                })
            },
            //获取报工时长
            difference(startTime, endTime) {
                const {
                    unitPrice,
                    pricingMethod,
                    goodProductNumber
                } = this.jcxxForm
                let dateStart = new Date(startTime)
                let dateEnd = new Date(endTime)
                let dateDiff = dateEnd.getTime() - dateStart.getTime() //时间差的毫秒数
                let dayDiff = Math.floor((dateDiff / (24 * 3600 * 1000)) * 24) //计算相差小时数
                let leave1 = dateDiff % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
                //计算相差分钟数
                let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
                let minutes = Math.floor(leave2 / (60 * 1000))
                this.hours = dayDiff
                this.min = minutes
                //总时长 若当前工序计件和计时都未配置标准效率时 若报工时长!=0时 默认实际效率的时长为1h0min0s 反之和标准效率时长一样
                this.totalDuration = this.workingHours ? (this.efficiencyHour + (this.efficiencyMinute / 60) + (this.efficiencySecond / 3600))
                    : 1
                //占比 报工时长 / 总时长
                this.percentage = (dayDiff + (minutes / 60)) / this.totalDuration
                //预计工资 == 报工时长 * 单价
                let wageHours = (dayDiff + (minutes / 60)).toFixed(2)
                if (pricingMethod == 1) this.jcxxForm.estimateWage = wageHours * unitPrice
                //实际效率
                this.realOutput = (goodProductNumber / this.percentage).toFixed(2)
                //达标率
                if(this.hours == 0 && this.min == 0){ //报工时长==0
                    this.jcxxForm.standardRate == '-'
                }else if(this.hours > 0 || this.min > 0){ //报工时长>0 && 标准效率有值时
                    this.jcxxForm.standardRate = this.workingHours ? 
                        (((goodProductNumber / this.percentage) / this.output) * 100).toFixed(2) + '%' : '-'
                }
            },
            //查看操作记录
            watchHistory() {
                this.$router.push({
                    path: '/productionManagement/jobBooking/operationHistory',
                    query: {
                        code: this.$route.query.workCode
                    }
                })
            },
            addBad() {
                let data = []
                data = this.badProData.filter(i => i.checked == true && i.number != undefined)
                this.jcxxForm.badProductList = data.map(i => `${i.blpx} ${i.number}`)
                this.map_badProductList = data.map(i => {
                    return {
                        badProductId: i.id,
                        num: i.number,
                    }
                })
                this.$refs.addBadPro.closeDialog()
            },
            numberChange() {
                const {
                    goodProductNumber,
                    badProductNumber,
                    pricingMethod,
                    unitPrice
                } = this.jcxxForm
                //报工数 == 良品数 + 不良品数
                this.jcxxForm.reportNumber = goodProductNumber + badProductNumber
                //预计工资 == 良品数 * 单价
                if (pricingMethod == 0) this.jcxxForm.estimateWage = goodProductNumber * unitPrice
                //实际效率
                this.realOutput = (goodProductNumber / this.percentage).toFixed(2)
                //达标率
                if(this.hours == 0 && this.min == 0){ //报工时长==0
                    this.jcxxForm.standardRate == '-'
                }else if(this.hours > 0 || this.min > 0){ //报工时长>0 && 标准效率有值时
                    this.jcxxForm.standardRate = this.workingHours ? 
                        (((goodProductNumber / this.percentage) / this.output) * 100).toFixed(2) + '%' : '-'
                }
            },
        }
    }
</script>

<style lang="less" scoped>
    .edit {
        padding: 20px;
        overflow-y: auto;

        .title {
            font-size: 18px;
            color: #1f273d;
        }

        .edit_header {
            margin-bottom: 10px;

            .title {
                vertical-align: middle;
                margin-right: 20px;
            }
        }

        .goBack {
            padding-top: 20px;
            text-align: center;

            .el-button+.el-button {
                margin-left: 30px;
            }

            .el-button--primary {
                padding: 7px 35px;
            }
        }

        .badStyle {
            height: 28px;
            border: 1px solid #DCDFE6;
            transition: all .2s;
        }

        .badStyle:hover {
            border: 1px solid #C0C4CC;
        }

        .descriptions {
            .record {
                float: right;
                padding: 0;
            }

            .chooseTime {
                display: flex;
                flex-wrap: nowrap;
                justify-content: space-between;

                code {
                    width: 45%;
                    display: flex;

                    span {
                        white-space: nowrap;
                    }
                }

                .el-input--mini {
                    margin-right: 5px;
                }
            }

            /deep/ .el-select,
            /deep/ .el-input-number,
            /deep/ .el-date-editor.el-input {
                width: 100%;
            }
        }

        /deep/ .el-row,
        .el-col {
            height: auto;
        }

        .el-form-item--mini.el-form-item.special {
            /deep/ .el-tag.el-tag--info .el-tag__close {
                display: none;
            }

            .el-select {
                /deep/ .el-input__suffix-inner {
                    display: none;
                }
            }
        }

        .el-form-item--mini.el-form-item.efficiency,.el-form-item--mini.el-form-item.unitPrice{
            display: flex;
            /deep/ .el-form-item__label{
                flex-shrink: 0;
            }
            /deep/ .el-form-item__content{
                display: flex;
                margin-left: 0 !important;
                .el-input--mini{
                    flex-shrink: 0;
                    width: 60px;
                }
                .el-input--mini:first-child{
                    width: 80px;
                }
                span{
                    white-space: nowrap;
                }
            }
        }

        .el-form-item--mini.el-form-item.unitPrice{
            .el-input--mini.unitPrice{
                width: auto !important;
                flex: auto;
            }
        }

        /deep/ .el-dialog__body {
            padding: 10px 50px;
        }
    }
</style>